import { apiClient } from '../config'

// 缓存管理
const cache = new Map()
const CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存

// 请求重试配置
const RETRY_CONFIG = {
  maxRetries: 3,
  retryDelay: 1000,
  retryCondition: (error) => {
    return error.response?.status >= 500 || error.code === 'NETWORK_ERROR'
  }
}

/**
 * 带缓存的请求函数
 */
async function cachedRequest(key, requestFn, useCache = true) {
  if (useCache && cache.has(key)) {
    const { data, timestamp } = cache.get(key)
    if (Date.now() - timestamp < CACHE_DURATION) {
      return data
    }
    cache.delete(key)
  }

  try {
    const result = await requestFn()
    if (useCache) {
      cache.set(key, { data: result, timestamp: Date.now() })
    }
    return result
  } catch (error) {
    console.error(`请求失败 (${key}):`, error)
    throw error
  }
}

/**
 * 带重试的请求函数
 */
async function retryRequest(requestFn, config = RETRY_CONFIG) {
  let lastError
  
  for (let attempt = 1; attempt <= config.maxRetries; attempt++) {
    try {
      return await requestFn()
    } catch (error) {
      lastError = error
      
      if (!config.retryCondition(error) || attempt === config.maxRetries) {
        throw error
      }
      
      console.warn(`请求失败，第 ${attempt} 次重试...`, error.message)
      await new Promise(resolve => setTimeout(resolve, config.retryDelay * attempt))
    }
  }
  
  throw lastError
}

/**
 * 清除缓存
 */
export function clearCache(pattern = null) {
  if (pattern) {
    for (const key of cache.keys()) {
      if (key.includes(pattern)) {
        cache.delete(key)
      }
    }
  } else {
    cache.clear()
  }
}
export const personalCenterService = {
  /**
   * 获取个人仪表板数据
   */
  async getDashboard() {
    return cachedRequest('dashboard', async () => {
      return retryRequest(async () => {
        const response = await apiClient.get('/personal/dashboard')
        return response
      })
    })
  },

  /**
   * 获取个人统计数据
   */
  async getStatistics() {
    try {
      const response = await apiClient.get('/personal/dashboard/statistics')
      return response
    } catch (error) {
      console.error('获取个人统计失败:', error)
      throw error
    }
  },

  /**
   * 获取个人活动记录
   */
  async getActivities(params = {}) {
    try {
      const response = await apiClient.get('/personal/activities', { params })
      return response
    } catch (error) {
      console.error('获取个人活动失败:', error)
      throw error
    }
  },

  /**
   * 获取我的工单
   */
  async getMyTickets(params = {}) {
    try {
      const response = await apiClient.get('/personal/tickets', { params })
      return response
    } catch (error) {
      console.error('获取我的工单失败:', error)
      throw error
    }
  },

  /**
   * 获取我创建的工单
   */
  async getCreatedTickets(params = {}) {
    try {
      const response = await apiClient.get('/personal/tickets/created', { params })
      return response
    } catch (error) {
      console.error('获取创建的工单失败:', error)
      throw error
    }
  },

  /**
   * 获取分配给我的工单
   */
  async getAssignedTickets(params = {}) {
    try {
      const response = await apiClient.get('/personal/tickets/assigned', { params })
      return response
    } catch (error) {
      console.error('获取分配的工单失败:', error)
      throw error
    }
  },

  /**
   * 获取个人工单统计
   */
  async getPersonalTicketStatistics() {
    try {
      const response = await apiClient.get('/personal/tickets/statistics')
      return response
    } catch (error) {
      console.error('获取个人工单统计失败:', error)
      throw error
    }
  },

  /**
   * 获取个人资料
   */
  async getProfile() {
    try {
      const response = await apiClient.get('/personal/profile')
      return response
    } catch (error) {
      console.error('获取个人资料失败:', error)
      throw error
    }
  },

  /**
   * 更新个人资料
   */
  async updateProfile(profileData) {
    try {
      const response = await retryRequest(async () => {
        return await apiClient.put('/personal/profile', profileData)
      })
      
      // 清除相关缓存
      clearCache('dashboard')
      clearCache('profile')
      
      return response
    } catch (error) {
      console.error('更新个人资料失败:', error)
      throw error
    }
  },

  /**
   * 修改密码
   */
  async changePassword(passwordData) {
    try {
      const response = await apiClient.put('/personal/password', passwordData)
      return response
    } catch (error) {
      console.error('修改密码失败:', error)
      throw error
    }
  },

  /**
   * 上传头像
   */
  async uploadAvatar(file) {
    try {
      // 将文件转换为base64
      const base64 = await fileToBase64(file)
      const response = await apiClient.post('/personal/avatar', { file: base64 })
      return response
    } catch (error) {
      console.error('上传头像失败:', error)
      throw error
    }
  },

  /**
   * 获取个人设置
   */
  async getSettings() {
    try {
      const response = await apiClient.get('/personal/settings')
      return response
    } catch (error) {
      console.error('获取个人设置失败:', error)
      throw error
    }
  },

  /**
   * 更新个人设置
   */
  async updateSettings(settings) {
    try {
      const response = await apiClient.put('/personal/settings', settings)
      return response
    } catch (error) {
      console.error('更新个人设置失败:', error)
      throw error
    }
  },

  /**
   * 获取个人通知
   */
  async getNotifications(params = {}) {
    try {
      const response = await apiClient.get('/personal/notifications', { params })
      return response
    } catch (error) {
      console.error('获取个人通知失败:', error)
      throw error
    }
  },

  /**
   * 标记通知为已读
   */
  async markNotificationAsRead(notificationId) {
    try {
      const response = await apiClient.put(`/personal/notifications/${notificationId}/read`)
      return response
    } catch (error) {
      console.error('标记通知失败:', error)
      throw error
    }
  },

  /**
   * 标记所有通知为已读
   */
  async markAllAsRead() {
    try {
      const response = await apiClient.put('/personal/notifications/read-all')
      return response
    } catch (error) {
      console.error('标记所有通知失败:', error)
      throw error
    }
  },

  /**
   * 获取个人偏好设置
   */
  async getPreferences() {
    try {
      const response = await apiClient.get('/personal/preferences')
      return response
    } catch (error) {
      console.error('获取个人偏好失败:', error)
      throw error
    }
  },

  /**
   * 更新个人偏好设置
   */
  async updatePreferences(preferences) {
    try {
      const response = await apiClient.put('/personal/preferences', preferences)
      return response
    } catch (error) {
      console.error('更新个人偏好失败:', error)
      throw error
    }
  }
}

/**
 * 文件转Base64工具函数
 */
function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
